package com.bjsxt;
//使用this作为线程对象锁    在不同线程中，相同对象中的synchronized会互斥
/*synchronized () 方法可以在任意一个类中的方法实现，不一定要继承Thread的类*/
/*定义程序员类*/
class Programmer01 {
    private String name;
    public Programmer01(String name){
        this.name=name;
    }
    //打开电脑
    //使用synchronized () 首先要考虑哪部分代码需要同步，
    // 再考虑让哪些线程在执行时具有互斥
    //在同一对象下有互斥
   synchronized public void computer(){

       try {
           System.out.println(this.name + "接通电源");
           Thread.sleep(500);
           System.out.println(this.name + "按下开机键");
           Thread.sleep(500);
           System.out.println(this.name + "系统启动中");
           Thread.sleep(500);
           System.out.println(this.name + "系统启动成功");
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
    synchronized public void coding(){
        try {
            System.out.println(this.name + "双击IDEA");
            Thread.sleep(500);
            System.out.println(this.name + "Idea启动完毕");
            Thread.sleep(500);
            System.out.println(this.name + "写代码");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
//开电脑线程
class Working01 implements Runnable{
    //将程序员对象传入来
    private Programmer01 p;
    //构造方法传入
    public Working01(Programmer01 p){
        this.p=p;
    }
    @Override
    public void run() {
        this.p.computer();
    }
}
//写代码线程
class Working02 implements Runnable{
    private Programmer01 p;
    public Working02(Programmer01 p){
        this.p=p;
    }
    @Override
    public void run() {
        this.p.coding();
    }
}
public class TestSynchronized02 {
    public static void main(String[] args) {
        Programmer01 p = new Programmer01("小二");
         new Thread(new Working01(p)).start();
         new Thread(new Working02(p)).start();
    }
}
